import React, { useState } from 'react';
import { Modal, Form, Row, Col, Input, TreeSelect, InputNumber, message } from 'antd';
import { FormInstance } from 'antd/es/form/Form';
import ASelect, { ASelectOptionType } from '@/components/SelfComp/ASelect';
import { ApiItem, ApiSelectTreeItem } from '@/types/api';
import { DataItem, FormModalProps } from '@/types/global';
import { formLayout, modalFormItemLayout, maxModalFormItemLayout } from '@/utils/commons';

type AddApiProps<T> = FormModalProps<T> & {
  apiTypeData: DataItem[];
  apiTreeData: ApiSelectTreeItem[];
}
// type AddApiPropsEx<T> = Omit<AddApiProps<T>, 'formData'>;

const FormItem = Form.Item;

const AddApiModal: React.FC<AddApiProps<ApiItem>> = (props) => {
  /** 接口url栏位是否可见，true-显示，false-不显示 */
  const [apiUrlVisible, setApiUrlVisible] = useState<boolean>(true);
  const { colon, modalTitle, modalWidth, modalVisible, apiTypeData, apiTreeData, loading, formData } = props;
  const { apiType, apiId, parentApiId } = formData;
  // 当勾选的是页面或弹窗，显示自己
  // 当勾选的是按钮或接口，显示父节点
  const tmpParentId = apiType === '1' || apiType === '3' ? apiId + '' : parentApiId + '';
  const formItemLayout = modalFormItemLayout;
  const formRef = React.createRef<FormInstance>();

  const onOk = () => {
    formRef.current!.validateFields().then(fieldsValue => {
      console.info(fieldsValue);
      const values = {
        ...fieldsValue
      };
      const { apiType } = values;
      if (apiType !== '4') {
        message.warn('只允许添加接口权限，请重新选择');
        return;
      }
      console.log('Received values of form: ', values);
      const { onHandlerOK } = props;
      if (onHandlerOK) {
        onHandlerOK({
          ...values
        });
      }
    }).catch();
  };

  const onCancel = () => {
    // 先清除form表单
    formRef.current!.resetFields();
    const { onHandlerCancel } = props;
    if (onHandlerCancel) {
      onHandlerCancel();
    }
  }

  /**
   * 菜单类型栏位改变事件
   * 默认情况下 onChange 里只能拿到 value
   */
  const apiTypeChange = (value: string, option: ASelectOptionType | ASelectOptionType[]) => {
    // 查询该功能码对应的交易信息
    // console.log('apiTypeChange');
    // 菜单类型为2-按钮时，显示按钮位置栏位
    formRef.current!.resetFields([
      'apiUrl'
    ]);
    if (value === '2' || value === '4') {
      setApiUrlVisible(true);
      return;
    }
    if (value === '1') {
      setApiUrlVisible(false);
    }
  }
  // console.log(formData);
  // console.log(tmpParentId);

  return (
    <Modal
      title={modalTitle}
      destroyOnClose
      maskClosable={false}
      width={modalWidth}
      open={modalVisible}
      confirmLoading={loading}
      onOk={onOk}
      onCancel={onCancel}>
      <Form layout={formLayout} ref={formRef}>
        <Row>
          <Col span={24}>
            <FormItem label='上级菜单' name='parentApiId' {...maxModalFormItemLayout} colon={colon}
              initialValue={tmpParentId}
            >
              <TreeSelect
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={apiTreeData}
                allowClear
                showSearch
                treeNodeFilterProp='title'
                placeholder='请选择'
              />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label='接口权限类型' name='apiType' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '接口权限类型必输' }
              ]}
              initialValue={'4'}
            >
              <ASelect dataSource={apiTypeData} onChange={apiTypeChange}/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='接口权限名称' name='apiName' {...formItemLayout} colon={colon}
              rules={[
                { max: 30, message: '接口权限名称最多允许输入30个字符' },
                { required: true, message: '接口权限名称必输' }
              ]}
            >
              <Input/>
            </FormItem>
          </Col>
        </Row>
        {
          !apiUrlVisible ? null :
          <Row>
            <Col span={24}>
              <FormItem label='接口url' name='apiUrl' {...maxModalFormItemLayout} colon={colon}
                rules={[
                  { required: apiUrlVisible, message: '接口url必输' },
                  { max: 50, message: '接口url最多允许输入50个字符' },
                ]}
              >
                <Input/>
              </FormItem>
            </Col>
          </Row>
        }
        <Row>
          <Col span={12}>
            <FormItem label='菜单图标' name='apiIcon' {...formItemLayout} colon={colon}>
              <Input/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label='接口权限编码' name='apiCode' {...formItemLayout} colon={colon}
              rules={[
                { max: 30, message: '接口权限编码最多允许输入30个字符' },
                { required: true, message: '接口权限编码必输' },
                { pattern: new RegExp(/^[A-Za-z][A-Za-z0-9-_:]{1,30}$/, 'g'), message: '接口权限编码只能以字母开头，由A-Za-z0-9组成，最大长度为30' }
              ]}
            >
              <Input/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='接口权限别名' name='apiAlias' {...formItemLayout} colon={colon}
              rules={[
                { max: 30, message: '接口权限别名最多允许输入30个字符' },
                { required: true, message: '接口权限别名必输' }
              ]}
            >
              <Input/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label='显示排序' name='apiSort' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '显示排序必输' }
              ]}
            >
              <InputNumber min={0} style={{ width: '100%' }}/>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
}

export default AddApiModal